package com.itheima.sc.impl.sms;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.sc.api.sms.SmsFlashApi;
import com.itheima.sc.mapper.sms.SmsFlashMapper;
import com.itheima.sc.mapper.sms.SmsFlashProductRelationMapper;
import com.itheima.sc.pojo.sms.FlashPromotion;
import com.itheima.sc.pojo.sms.FlashPromotionProductRelation;
import com.itheima.sc.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class SmsFlashImpl implements SmsFlashApi {

    @Autowired
    private SmsFlashMapper smsFlashMapper;
    @Autowired
    private SmsFlashProductRelationMapper relationMapper;

    //秒杀活动列表
    public PageResult list(String keyword, int page, int pageSize) {
        //创建分页查询
        Page<FlashPromotion> ipage = new Page<>(page, pageSize);
        //创建条件查询结构
        LambdaQueryWrapper<FlashPromotion> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(keyword), FlashPromotion::getTitle, keyword);
        ipage = smsFlashMapper.selectPage(ipage, wrapper);
        PageResult<FlashPromotion> pageResult = new PageResult<FlashPromotion>(page, pageSize, Convert.toInt(ipage.getTotal()), Convert.toInt(ipage.getTotal() / pageSize), ipage.getRecords());
        return pageResult;
    }

    //添加秒杀活动
    public void addFlash(FlashPromotion flashPromotion) {
        smsFlashMapper.insert(flashPromotion);
    }

    //删除秒杀活动    三思后行
    public void delete(Long id) {
            //下线才能够删除
            smsFlashMapper.deleteById(id);

    }
    public int findStatus(Long id) {
        //1.首先判断有与他有关的关系 是否存在数据
        LambdaQueryWrapper<FlashPromotionProductRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlashPromotionProductRelation::getFlashPromotionId, id);
        List<FlashPromotionProductRelation> relations = relationMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(relations)) {
            //存在数据 先删除关系表中的数据
            List<Long> ids = CollUtil.getFieldValues(relations, "id", Long.class);
            relationMapper.deleteBatchIds(ids);
        }
        //2.查询活动的状态 上线中的状态不能删除
        FlashPromotion flashPromotion = smsFlashMapper.selectById(id);
        return flashPromotion.getStatus();
    }

    //更新上下线的状态
    public void updateFlash(FlashPromotion flashPromotion) {
        smsFlashMapper.updateById(flashPromotion);
    }

    //通过id查询用户的详细信息
    public FlashPromotion selectFlash(Long id) {
        return smsFlashMapper.selectById(id);
    }




}
